package com.chexiehui.jc.ui.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aries.ui.view.radius.RadiusTextView;
import com.aries.ui.widget.alert.UIAlertDialog;
import com.blankj.utilcode.util.PhoneUtils;
import com.blankj.utilcode.util.StringUtils;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpActivity;
import com.chexiehui.jc.entity.CarInfo;
import com.chexiehui.jc.entity.DictInfo;
import com.chexiehui.jc.entity.SpecialCarInfo;
import com.chexiehui.jc.mvp.car.SpecialCarDetailsCovenant;
import com.chexiehui.jc.mvp.car.SpecialCarDetailsPresenter;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.utils.GlideUtil;
import com.chexiehui.jc.widget.LoadingLayout;
import com.chexiehui.jc.widget.NineGridTestLayout;
import com.chexiehui.jc.widget.NoScrollListView;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 特价车详情
 */
public class SpecialCarDetailsActivity extends BaseMvpActivity<SpecialCarDetailsPresenter> implements SpecialCarDetailsCovenant.View {

    @BindView(R.id.tv_car_name)
    TextView tvCarName;
    @BindView(R.id.tv_car_price)
    TextView tvCarPrice;
    @BindView(R.id.tv_factory_price)
    TextView tvFactoryPrice;
    @BindView(R.id.tv_agent_price)
    TextView tvAgentPrice;
    @BindView(R.id.tv_car_time)
    TextView tvCarTime;
    @BindView(R.id.nslv_car_params)
    NoScrollListView nslvCarParams;
    @BindView(R.id.iv_shop_img)
    ImageView ivShopImg;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.tv_shop_address)
    TextView tvShopAddress;
    @BindView(R.id.rl_shop_panel)
    RelativeLayout rlShopPanel;
    @BindView(R.id.tv_parameter_config)
    TextView tvParameterConfig;
    @BindView(R.id.rtv_call)
    RadiusTextView rtvCall;
    @BindView(R.id.loadingLayout)
    LoadingLayout loadingLayout;
    @BindView(R.id.ll_car_imgs_panel)
    LinearLayout llCarImgsPanel;
    @BindView(R.id.ngtv_car_images)
    NineGridTestLayout ngtvCarImages;
    private String carId;
    private SpecialCarInfo carInfo;
    private ArrayList<CarInfo> carModelData;

    @Override
    protected void beforeSetView() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            carId = bundle.getString("id");
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String id = bundle.getString("id");
            if (!StringUtils.isTrimEmpty(id) && getCarId().equals(id)) {
                return;
            }
            carId = id;
        } else {
            return;
        }
        if (StringUtils.isTrimEmpty(getCarId())) {
            loadingLayout.setStatus(LoadingLayout.Empty);
            loadingLayout.setEmptyText("暂无车源信息");
            return;
        }
        loadingLayout.setStatus(LoadingLayout.Loading);
        mvpPresenter.getCarInfo();
    }

    @Override
    protected void setTitleBar() {
        titleBar.setTitleMainText("车源详情");
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_special_car_details;
    }

    @Override
    protected void initView(Bundle var1) {
        loadingLayout.setStatus(LoadingLayout.Loading);
        if (StringUtils.isTrimEmpty(carId)) {
            loadingLayout.setStatus(LoadingLayout.Empty);
            loadingLayout.setEmptyText("暂无车源信息");
            return;
        }
        loadingLayout.setOnReloadListener(v -> {
            loadingLayout.setStatus(LoadingLayout.Loading);
            mvpPresenter.getCarInfo();
        });
        mvpPresenter.getCarInfo();
    }

    private void setCarInfo() {
        tvCarName.setText(carInfo.getName());
        tvCarTime.setText(carInfo.getCreateTime());
        tvCarPrice.setText(carInfo.getSpecialPriceStr());
        tvFactoryPrice.setText(carInfo.getNewPriceStr());
        tvAgentPrice.setText(carInfo.getAgentPriceStr());
        tvAgentPrice.setVisibility(StringUtils.isTrimEmpty(carInfo.getAgentPriceStr()) ? View.GONE : View.VISIBLE);
        tvShopName.setText(carInfo.getShopModel().getName());
        tvShopAddress.setText(carInfo.getShopModel().getAdress());
        GlideUtil.loadImageViewCrop(mContext, carInfo.getShopModel().getShopImage(),
                ivShopImg, R.drawable.shape_square, R.drawable.shape_square);
        List<DictInfo> paramsList = new ArrayList<>();
        paramsList.add(new DictInfo("颜色", carInfo.getColor()));
        paramsList.add(new DictInfo("类型", carInfo.getType()));
        paramsList.add(new DictInfo("车源所在地", carInfo.getSource()));
        paramsList.add(new DictInfo("手续", carInfo.getProcedures()));
        paramsList.add(new DictInfo("销售区域", carInfo.getSaleArea()));
        paramsList.add(new DictInfo("排放标准", carInfo.getOutputType()));
        paramsList.add(new DictInfo("备注", carInfo.getRemark()));
        nslvCarParams.setAdapter(new CommonAdapter<DictInfo>(mContext, R.layout.item_car_params, paramsList) {
            @Override
            protected void convert(ViewHolder viewHolder, DictInfo item, int position) {
                viewHolder.setText(R.id.tv_item_param_name, item.getKey());
                viewHolder.setText(R.id.tv_item_param_value, item.getValue());
            }
        });
        if (carInfo.getProcessImgs() != null && carInfo.getProcessImgs().size() > 0) {
            llCarImgsPanel.setVisibility(View.VISIBLE);
            ngtvCarImages.setUrlList(carInfo.getProcessImgs());
        } else {
            llCarImgsPanel.setVisibility(View.GONE);
        }
    }

    @Override
    protected SpecialCarDetailsPresenter createPresenter() {
        return new SpecialCarDetailsPresenter(this);
    }

    @Override
    public void onGetCarInfoSuccess(BaseModel<SpecialCarInfo> successResult) {
        loadingLayout.setStatus(LoadingLayout.Success);
        carInfo = successResult.getData();
        setCarInfo();
    }

    @Override
    public void onGetCarInfoFailure(BaseModel<Object> failureResult) {
        if (failureResult.getResultCode() == Constants.PAGE_DATA_EMPTY) {
            loadingLayout.setStatus(LoadingLayout.Empty);
            loadingLayout.setEmptyText(failureResult.getResultInfo());
        } else {
            loadingLayout.setStatus(LoadingLayout.Error);
            loadingLayout.setErrorText(failureResult.getResultInfo());
        }
    }

    @Override
    public String getCarId() {
        return carId == null ? "" : carId;
    }

    @OnClick({R.id.rl_shop_panel, R.id.tv_parameter_config, R.id.rtv_call})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_shop_panel:
                if (!StringUtils.isTrimEmpty(carInfo.getShopModel().getShopId())) {
                    startActivity(ShopDetailsActivity.class,
                            new BundleBuilder().putString("id", carInfo.getShopModel().getShopId())
                                    .create());
                }
                break;
            case R.id.tv_parameter_config:
                if (carModelData == null) {
                    carModelData = new ArrayList<>();
                    for (int i = 0; i < carInfo.getCarBrieflies().size(); i++) {
                        carModelData.addAll(carInfo.getCarBrieflies().get(i).getCarList());
                    }
                }
                if (carModelData.size() <= 0) {
                    showToast("暂无参数配置数据");
                    return;
                }
                startActivity(CarBrandParameterActivity.class,
                        new BundleBuilder()
                                .putSerializable("compareList", carModelData)
                                .create());
                break;
            case R.id.rtv_call:
                if (StringUtils.isTrimEmpty(carInfo.getShopModel().getTel())) {
                    showToast("暂无电话信息");
                    return;
                }
                UIAlertDialog dialog = new UIAlertDialog.DividerIOSBuilder(mContext)
                        .setTitle("拨打电话")
                        .setMessage(carInfo.getShopModel().getTel())
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).setPositiveButton("拨打", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                callPhone();
                                dialog.dismiss();
                            }
                        }).create();
                dialog.show();
                break;
        }
    }

    private void callPhone() {
        AndPermission.with(this)
                .permission(Permission.PHONE)
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        PhoneUtils.call(carInfo.getShopModel().getTel());
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                        if (AndPermission.hasAlwaysDeniedPermission(mContext, deniedPermissions)) {
                            AndPermission.defaultSettingDialog(mContext, Constants.REQUEST_CODE_LOACTION).show();
                        } else {
                            showToast(getStringSource(R.string.app_name) + "需要您授权电话权限");
                        }
                    }
                })
                .requestCode(Constants.REQUEST_CODE_CARAME)
                .rationale((requestCode, rationale) -> AndPermission.rationaleDialog(mContext, rationale).show()).start();
    }

}
